import React, { useRef, useEffect, useState } from 'react'
import { View, Text, ScrollView } from '@tarojs/components'
import Taro, { getCurrentInstance, useDidShow } from '@tarojs/taro'
import { useSelector, useDispatch } from 'react-redux'
import { useImmer } from 'use-immer'
import { AtTabs, AtTabsPane } from 'taro-ui'
import {
  SpFilterBar,
  SpTagBar,
  SpGoodsItem,
  SpSearchBar,
  SpPage,
  SpScrollView,
  SpImage,
  SpPrice
} from '@/components'
import { fetchUserFavs } from '@/store/slices/user'
import doc from '@/doc'
import api from '@/api'
import { pickBy, classNames, getDistributorId, entryLaunch, VERSION_STANDARD } from '@/utils'
import S from '@/spx'

import './search.scss'

const initialState = {
  leftList: [],
  rightList: [],
  brandList: [],
  brandSelect: [],
  filterList: [
    { title: '综合' },
    { title: '销量' },
    { title: '价格', icon: 'icon-shengxu-01' },
    { title: '价格', icon: 'icon-jiangxu-01' }
  ],
  curFilterIdx: 0,
  tagList: [],
  curTagIdx: 0,
  keywords: '',
  show: false,
  fixTop: 0,
  routerParams: null,
  card_id: null, // 兑换券
  tabsList: [
    {
      title: '商品'
    },
    {
      title: '店铺'
    }
  ],
  curTabsIdx: 0,
  storeBase: {
    backgroundColor: '#fff',
    imgUrl: '',
    padded: true,
    subtitle: '',
    title: ''
  },
  storeData: [],
  storeSeletedTags: []
}

function Search() {
  const $instance = getCurrentInstance()
  const [state, setState] = useImmer(initialState)
  const {
    keywords,
    leftList,
    rightList,
    brandList,
    brandSelect,
    curFilterIdx,
    filterList,
    tagList,
    curTagIdx,
    show,
    fixTop,
    routerParams,
    tabsList,
    curTabsIdx,
    storeBase,
    storeData,
    storeSeletedTags
  } = state
  const [isShowSearch, setIsShowSearch] = useState(false)
  const { cat_id, main_cat_id, tag_id, card_id, user_card_id } = routerParams || {}
  const { shopInfo } = useSelector((state) => state.shop)
  const dispatch = useDispatch()

  const storeRef = useRef()
  useEffect(() => {
    if (S.getAuthToken()) {
      dispatch(fetchUserFavs())
    }
  }, [])

  useEffect(() => {
    // card_id, user_card_id: 兑换券参数
    entryLaunch.getRouteParams($instance.router.params).then((params) => {
      const { cat_id, main_cat_id, tag_id, card_id, user_card_id } = params

      setState((draft) => {
        draft.routerParams = {
          cat_id,
          main_cat_id,
          tag_id,
          card_id,
          user_card_id
        }
      })
    })
  }, [])

  useEffect(() => {
    if (routerParams) {
      storeRef.current.reset()
    }
  }, [routerParams])


  const handleOnFocus = () => {
    setIsShowSearch(true)
  }

  const handleOnChange = (val) => {
    setState((v) => {
      v.keywords = val
    })
  }

  const handleOnClear = async () => {
    await setState((draft) => {
      draft.leftList = []
      draft.rightList = []
      draft.keywords = ''
    })
    setIsShowSearch(false)
  }

  const handleSearchOff = async () => {
    setIsShowSearch(false)
    await setState((v) => {
      v.keywords = ''
    })
  }

  const handleConfirm = async (val) => {
    setIsShowSearch(false)
    await setState((draft) => {
      draft.leftList = []
      draft.rightList = []
      draft.storeData = []
      draft.keywords = val
    })
    storeRef.current.reset()
  }
  const handleStoreClick = (id, type) => {
    if (type === 'virtual_store') {
      const url = `/marketing/pages/distribution/shop-home?featuredshop=${id}`
      Taro.navigateTo({
        url
      })
    } else {
      const url = `/subpages/store/index?id=${id}`
      Taro.navigateTo({
        url
      })
    }
  }

  const handleGoodsClick = (item) => {
    const url = `/pages/item/espier-detail?id=${item.goodsId}&dtid=${item.distributor_id}`
    Taro.navigateTo({
      url
    })
  }

  const storeFetch = async ({ pageIndex, pageSize }) => {
    let params = {
      page: pageIndex,
      pageSize,
      keywords: keywords,
      item_type: 'normal',
      is_point: false
    }
    const { list, total } = await api.item.takeawayShopList(params)
    setState((v) => {
      v.storeData = [...storeData, ...list]
    })
    return { total: total }
  }

  return (
    <SpPage
      scrollToTopBtn
      className={classNames('page-item-list', {
        'has-tagbar': tagList.length > 0
      })}
    >
      <View className='search-wrap'>
        {/* 兑换券选择店铺 */}
        {VERSION_STANDARD && card_id && (
          <View
            className='store-picker'
            onClick={() => {
              Taro.navigateTo({
                url: '/subpages/store/list'
              })
            }}
          >
            <View className='shop-name'>{shopInfo.store_name || '暂无店铺信息'}</View>
            <Text className='iconfont icon-qianwang-01'></Text>
          </View>
        )}
        <SpSearchBar
          keyword={keywords}
          placeholder='搜索'
          onFocus={handleOnFocus}
          onChange={handleOnChange}
          onClear={handleOnClear}
          onCancel={handleSearchOff}
          onConfirm={handleConfirm}
        />
      </View>
      <SpScrollView className='item-list-scroll' auto={false} ref={storeRef} fetch={storeFetch}>
        <View className={`wgt wgt-store ${storeBase.padded ? 'wgt__padded' : null}`}>
          {storeBase.title && (
            <View className='wgt-head'>
              <View className='wgt-hd'>
                <Text className='wgt-title'>{storeBase.title}</Text>
                <Text className='wgt-subtitle'>{storeBase.subtitle}</Text>
              </View>
            </View>
          )}
          {storeData?.map((item) => (
            <View
              className='store-wrap'
              key={item.id}
              style={{ backgroundColor: storeBase.backgroundColor || '#FFF' }}
            >
              <View
                className='store-info'
                onClick={handleStoreClick.bind(this, item.id, item.type)}
              >
                <SpImage
                  className='store-logo'
                  src={item.logo}
                  mode='scaleToFill'
                  width={100}
                  height={100}
                />
                <View className='store-title'>
                  <View className='store-name'>{item.name}</View>
                  <View className='store-tags'>
                    {storeSeletedTags.length > 0 &&
                      storeSeletedTags.map((itemy) => (
                        <Text className='store-tags-item' key={itemy.tag_id}>
                          {itemy.tag_name}
                        </Text>
                      ))}
                  </View>
                </View>
              </View>
              {storeBase.imgUrl && <SpImage className='store-banner' src={storeBase.imgUrl} />}
              <ScrollView scrollX className='store-goods'>
                {item.items.map((goods) => (
                  <View
                    className='store-goods__item'
                    onClick={handleGoodsClick.bind(this, goods)}
                    key={goods.goodsId}
                  >
                    <SpImage
                      className='store-goods__item-thumbnail'
                      src={goods.pics}
                      mode='aspectFill'
                      width={218}
                      height={218}
                    />
                    <View
                      className='store-goods__item-price'
                      style={{ color: storeBase.borderColor }}
                    >
                      <SpPrice value={goods.price / 100} />
                    </View>
                  </View>
                ))}
              </ScrollView>
            </View>
          ))}
        </View>
      </SpScrollView>
    </SpPage>
  )
}

export default Search
